require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIHeroChipResolve = {};
HelperFunc.SetUIEnv(UIHeroChipResolve)
local this = UIHeroChipResolve;

this.gameObject = nil;
this.transform = nil;
this.LuaBehaviour = nil;

this.hasInit = false;

this.btnFilterBtn = nil;
this.btnConfirmBtn = nil;
this.btnSelectAllBtn = nil;
this.btnResetBtn = nil;
this.btnBackBtn = nil;
this.btnMessageBtn = nil;
--this.listItemGrid;
this.objHasSelectGroup = nil;

--this.tableGetItem; -- obj:GameObject itemPos: item节点位置 numTxt: 数量文本

this.itemConfig = nil;
this.heroConfig = nil;
this.heroRankConfig = nil;
--[[
    obj: GameObject
    modelId: modelId
    num：数量
]]
---@type HeroResolveItem[]
this.tableSelectedItem = nil;
--[[
    key:modelId
    value: itemData
]]
this.tableUnSelectInfo = nil;

this.timer = nil;
this.filterData = nil;
---@type GList
this.selectedItemList = nil
this.listItemGrid = nil
---@type HeroResolveItem[]
this.curSelectedList = {}
---@type HeroResolveItem
this.tableGetItem = nil
this.itemDataList = {}
this.MAX_COUNT = 12
function UIHeroChipResolve.Init()--todo 应该小写 暂时先大写
    if itemConfig == nil then
        itemConfig = G.dataTable["t_item"];
        heroConfig = G.dataTable["t_hero"];
        heroRankConfig = G.dataTable["t_herorank"];
    end
    local name,package = getUIName(PanelNames.UIHeroChipResolve);
    panelMgr:ShowUI(name,package, this.onCreate, Config.useLocalUI);
end
---@param obj GComponent
function UIHeroChipResolve.onCreate(obj)
    --gameObject = obj;
    --transform = obj.transform;
    --LuaBehaviour = transform:GetComponent('LuaBehaviour');
    
    if not hasInit then
        hasInit = true;
        btnFilterBtn = obj:GetChild("FilterBtn")
        btnConfirmBtn = obj:GetChild("ConfirmBtn")
        btnSelectAllBtn = obj:GetChild("SelectAllBtn")
        btnResetBtn = obj:GetChild("ResetBtn")
        btnBackBtn = obj:GetChild("BackBtn")
        btnMessageBtn = obj:GetChild("MessageBtn")
        listItemGrid = obj:GetChild("selectItemGrid")
        listItemGrid.itemRenderer = this.setData
        --objHasSelectGroup = obj:GetChild("HasSelectGroup").gameObject;
        selectedItemList = obj:GetChild("selectedGrid")

        tableGetItem = {
            item = HeroResolveItem.New(),

            numTxt = obj:GetChild("GetItemNum")
        }
        tableGetItem.item:EnableClick(false)
        tableGetItem.item:Bind(obj:GetChild("GetItem"))
        --[[local trGetItem = obj:GetChild("GetItemPos");
        tableGetItem = {
            obj = trGetItem.gameObject,
            itemPos = trGetItem:Find("ItemPos").gameObject,
            numTxt = trGetItem:Find("GetItemNum"):GetComponent("TextMeshProUGUI");
        };]]

        tableSelectedItem={};
        local singleItemConfig = itemConfig[tostring(CurrencyEnum.EliteCertificate)];
        local childCount = selectedItemList.numItems;
        for i = 0, childCount-1 do
            local obj = selectedItemList:GetChildAt(i)
            ---@type HeroResolveItem
            local item = HeroResolveItem.New()
            item:Bind(obj)
            item:EnableClick(false)
            item:RefreshMaterial(singleItemConfig.f_Icon)
            --[[resMgr:LoadIconFromPrefab("itemAtlas",singleItemConfig.f_Icon,function (sp)
                obj.transform:Find("MaterialPos/Icon"):GetComponent("Image").sprite = sp;
            end);]]
            table.insert(tableSelectedItem,item);
        end
        this.poolMgr = logicMgr.PoolManager.New(HeroResolveItem)
        this.addEvent();
    end
    curSelectedList = {}
    this.refresh();
end

function UIHeroChipResolve.addEvent()
    btnFilterBtn.onClick:Add(this.onClickFilter)
    btnConfirmBtn.onClick:Add(this.onClickConfirm)
    btnSelectAllBtn.onClick:Add(this.onClickSelectAll)
    btnResetBtn.onClick:Add(this.onClickReset)
    btnBackBtn.onClick:Add(this.onClickClose)
    btnMessageBtn.onClick:Add(this.onClickMessage)


end

function UIHeroChipResolve.removeEvent()
    btnFilterBtn.onClick:Clear()
    btnConfirmBtn.onClick:Clear()
    btnSelectAllBtn.onClick:Clear()
    btnResetBtn.onClick:Clear()
    btnBackBtn.onClick:Clear()
    btnMessageBtn.onClick:Clear()

end

function UIHeroChipResolve.LocalListenEvent()
    ListenEvent(Config.EventType.ItemResolve,this.ReceiveItemResolveMsg);
end

function UIHeroChipResolve.LocalCloseEvent()
    CloseEvent(Config.EventType.ItemResolve,this.ReceiveItemResolveMsg);
    if timer~=nil then
        timer:Stop();
    end
end

function UIHeroChipResolve.OnDestroy()
    this.removeEvent();
end

function UIHeroChipResolve.OnEnable()
    this.LocalListenEvent();
end

function UIHeroChipResolve.OnDisable()
    this.LocalCloseEvent();
end


function UIHeroChipResolve.refresh()
    local singleItemConfig = itemConfig[tostring(CurrencyEnum.EliteCertificate)];
    local itemData = {
        icon=singleItemConfig.f_Icon,
        quality=singleItemConfig.f_Quality
    }
    tableGetItem.item:Refresh(itemData)
    tableGetItem.numTxt.text = "0"

    tableUnSelectInfo = {};
    for key, value in pairs(heroConfig) do
        local modelId = value.f_HeroPiece;
        if modelId ~= nil and modelId >0 then
            local singleItem = logicMgr.ItemManager.getItemConstDatabyModelId(modelId);
            singleItem.itemModelId = modelId;
            singleItem.num = logicMgr.ItemManager.getItemCountbyModelId(modelId);
            if singleItem~= nil and singleItem.num>0 then
                if filterData == nil or not table.contains(filterData.list,modelId) then
                    singleItem.num = this.getUnSelectCount(value.f_HeroID,singleItem.num);
                    if singleItem.num>0 then
                        tableUnSelectInfo[modelId] = singleItem;
                    end
                end
            end
        end
    end

    this.setChipList();
    this.refreshSelectedShow();

    if timer == nil then
        timer = Timer.New(this.shakeHasSelectAni,2,-1,false);
    else
        timer:Stop();
        timer:Reset(this.shakeHasSelectAni,2,-1,false);
    end
    timer:Start();
end

function UIHeroChipResolve.getUnSelectCount(heroModelId,chipCount)
    if filterData == nil or not filterData.isRemainRankChip then
        return chipCount;
    end
    local heroData = logicMgr.HeroManager.getHeroDatabyModelId(heroModelId,true);
    if heroData== nil then
        return chipCount;
    end
    local remainCount =0;
    if tonumber(heroData["partnerId"]) < 10000 then -- 未获得
        remainCount = remainCount+ logicMgr.HeroManager.GetHeroConfigbyModelId(heroModelId).f_HeroSynthesis;
    end
    local singleRankConfig = heroRankConfig[tostring(heroModelId*10+heroData.star)];
    while singleRankConfig~= nil do
        local chipCostStr = singleRankConfig.f_RankChipCost;
        if chipCostStr == nil or #chipCostStr ==0 then
            break;
        end
        local chipCost = decodeJsonStrToTabel(chipCostStr);
        remainCount = remainCount+ chipCost[2];
        singleRankConfig = heroRankConfig[tostring(singleRankConfig.f_HeroStarNext)];
    end
    chipCount = chipCount- remainCount;
    if chipCount<=0 then
        chipCount =0;
    end
    return chipCount;
end

function UIHeroChipResolve.getSortUnSelectList()
    local itemInfoList = {};
    for key, value in pairs(tableUnSelectInfo) do
        local data= {
            modelId = key,
            quality = value.quality,
            icon = value.icon,
            itemModelId = value.itemModelId,
            num = value.num
        };
        table.insert(itemInfoList,data);
    end
    table.sort(itemInfoList,function (a,b)
        if a.quality ~= b.quality then
            return a.quality> b.quality;
        end
        return a.itemModelId > b.itemModelId;
    end);
    return itemInfoList;
end

function UIHeroChipResolve.setChipList()
    itemDataList = this.getSortUnSelectList();
    listItemGrid.numItems = #itemDataList
    --listItemGrid:setDataByJsonArray(getJsonStr(itemInfoList));
end
function UIHeroChipResolve.ClickCheckMax()
    return #curSelectedList >= MAX_COUNT
end
---@param item HeroResolveItem
function UIHeroChipResolve.ClickChangeNum(item)
    ---@type HeroResolveItem
    local selectItem
    local flag = true
    for k,v in pairs(curSelectedList) do
        if v.modelId == item.data.modelId then
            selectItem = v
            v.num = item:GetNeedResolveNum()
            if v.num == 0 then
                table.remove(curSelectedList,k)
                break
            end
            flag = false
            break
        end
    end
    if flag and item:GetNeedResolveNum() > 0 then
        local d = clone(item.data)
        d.num = item:GetNeedResolveNum()
        table.insert(curSelectedList,d)
    end
    this.refreshSelectedShow();
end
function UIHeroChipResolve.setData(index,itemObj)

    index = index + 1
    local itemData = itemDataList[index]
    ---@type HeroResolveItem
    local item = this.poolMgr:GetBindScript(itemObj)
    item:Refresh(itemData,this.ClickChangeNum,this.ClickCheckMax)
end

function UIHeroChipResolve.refreshSelectedShow() -- 刷新已选择的信物
    local eliteCertificateCount =0;

    for k,v in pairs(tableSelectedItem) do
        local data = curSelectedList[k]
        if not data then
            v:Visible(false)
        else
            v:Visible(true)
            v:Refresh(data)
            local f = tableUnSelectInfo[data.modelId].itemFunction
            local count = 0
            if f and f ~= "" then
                local str = decodeJsonStrToTabel(f)
                if #str == 2 then
                    count = tonumber(str[2])
                    eliteCertificateCount = eliteCertificateCount + count
                end
            end
            v:RefreshMaterialNum(getNumString(count))
        end
        --if v.curNum == 0 then
       --     v:Visible(false)
        --else
            -- 刷新item
            --[[local itemInfo = tableUnSelectInfo[tableSelectedItem[i].modelId];
            local ctrItem = CtrlManager.GetCtrl(PanelNames.Item);
            local curItemItem = trItemPos:GetChild(0);
            local curItemData = {
                quality = itemInfo.quality,
                level = itemInfo.level,
                icon = itemInfo.icon,
                num = tableSelectedItem[i].num
            };
            ctrItem.initData(curItemItem,curItemData,LuaBehaviour);
            -- 计算材料
            local singleElitCertificateCount = itemInfo["itemFunction"]~=nil and tonumber(itemInfo["itemFunction"]) or 0;
            eliteCertificateCount = eliteCertificateCount+ singleElitCertificateCount;
            tableSelectedItem[i].obj.transform:Find("MaterialPos/Num"):GetComponent("TextMeshProUGUI").text = getNumString(singleElitCertificateCount);
            ]]
        --end
        --tableGetItem.numTxt.text = getNumString(eliteCertificateCount);
    end
    tableGetItem.numTxt.text = getNumString(eliteCertificateCount);
end


function UIHeroChipResolve.onClickFilter()
    
    showUI(PanelNames.UIHeroChipFilter,function (data)
        filterData =data;
        this.refresh();
    end,filterData);
end


function UIHeroChipResolve.onClickConfirm()
    local data ={};
    for k, v in pairs(curSelectedList) do
        local itemId = logicMgr.ItemManager.getItemIdByModelId(v.modelId);
        local itemInfo = logicMgr.ItemManager.getItemData(itemId);
        local singleData ={
            itemId = itemId,
            num = v.num,
            itemModelId = v.modelId,
            quality = itemInfo.quality,
            gridId = itemInfo.gridId,
        };
        table.insert(data,singleData);
    end
    --[[for key, value in pairs(tableSelectedItem) do
        if value.itemId~=0 and value.num>0 then
            local itemId = logicMgr.ItemManager.getItemIdsByModelId(value.modelId)[1];
            local itemInfo = logicMgr.ItemManager.getItemData(itemId);
            local singleData ={
                itemId = itemId,
                num = value.num,
                itemModelId = value.modelId,
                quality = itemInfo.quality,
                gridId = itemInfo.gridId,
            };
            printTable(singleData);
            table.insert(data,singleData);
        end
    end]]
    if #data>0 then
        itemHandler.sendResolveItem(data);
    end
end


function UIHeroChipResolve.onClickSelectAll()
    this.onClickReset();
    itemDataList = this.getSortUnSelectList();
    for k, v in pairs(itemDataList) do
        if k < MAX_COUNT then
            table.insert(curSelectedList,clone(v))
            v.curNum = 0
        end
    end
    listItemGrid.numItems = #itemDataList

    --[[for i = 1, #tableSelectedItem do
        if i<= #unselectSortList then
            local modelId = unselectSortList[i].modelId;
            tableSelectedItem[i].modelId = modelId
            tableSelectedItem[i].num = tableUnSelectInfo[modelId].num;
            tableUnSelectInfo[modelId].num =0;
        end
    end]]
    --this.setChipList(true);
    this.refreshSelectedShow();
end


function UIHeroChipResolve.onClickReset()
    table.clear(curSelectedList)
    --[[for i = 1, #tableSelectedItem do
        if tableSelectedItem[i].modelId~= 0 then
            local unselectInfo = tableUnSelectInfo[tableSelectedItem[i].modelId];
            unselectInfo.num = unselectInfo.num+ tableSelectedItem[i].num;
            tableSelectedItem[i].num = 0;
            tableSelectedItem[i].modelId =0;
        end
    end]]
    this.setChipList();
    this.refreshSelectedShow();
end

function UIHeroChipResolve.onClickClose()
    closeUI(PanelNames.UIHeroChipResolve);
end


function UIHeroChipResolve.onClickMessage()
    log('onClickMessage');
end

function UIHeroChipResolve.shakeHasSelectAni()
    for k,v in pairs(tableSelectedItem) do
        v:VisibleMat(not v:IsMatVisible())
    end
end
function UIHeroChipResolve.ReceiveItemResolveMsg()
    table.clear(curSelectedList)
    this.refresh()
end
return UIHeroChipResolve;
